<?php

namespace app\admin\controller\card;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 卡包
 *
 * @icon fa fa-circle-o
 */
class Kabaw extends Backend
{

    /**
     * Kabaw模型对象
     * @var \app\common\model\card\Kabaw
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\card\Kabaw;
        $this->view->assign("lifespanDataList", $this->model->getLifespanDataList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    protected function check($params){
        $data=[
            ['name', 'require', '名称不能为空'],
            ['illustrate', 'require', '详细说明不能为空'],
            ['event', 'require', '请添加卡券类型'],
            ['all_price', 'require', '请输入总价格'],
        ];
        $validate = new \think\Validate($data);
        if (!$validate->check($params)) {
            $this->error('提交失败：' . $validate->getError());
        }
        if($params["fate"]<=0) $this->error('提交失败：领取天数请填写大于0的数');
        if(!preg_match("/^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/",$params["all_price"])) $this->error('价格格式错误');
        //if($params["lifespan_data"]==0 && (empty($params["start_time"]) || empty($params["end_time"]))) $this->error('提交失败：开始和结束时间不能为空');
        $event=json_decode($params["event"],true);
        if(empty($event)) $this->error('提交失败：请选择卡券类型' );
        foreach ($event as $k=>$v){
            if(empty($v["card_type_id"])) $this->error('提交失败：请选择卡券类型' );
            if(empty($v["number"])) $this->error('提交失败：请输入次数' );
            //if(empty($v["price"])) $this->error('提交失败：请输入单次价格' );
            //if(empty($v["all_price"])) $this->error('提交失败：请输入总价格' );
        }
        $event=json_decode($params["event"],true);
        $arr= array_column($event,"card_type_id");
        $num = array_count_values($arr);
        foreach ($num as $v){
            if($v>1) $this->error('提交失败：不能添加相同类型' );
        }
        return true;
    }
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {

            $typeList=\app\common\model\card\Type::all();
            $this->assign("typeList",$typeList);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        $res=$this->check($params);
        if(!$res) return $res;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            /*if($params["lifespan_data"]==1){
                unset($params["start_time"]);
                unset($params["end_time"]);
            }else{
                unset($params["fate"]);
            }*/
            $event=json_decode($params["event"],true);
            unset($params["event"]);
            $params["createtime"]=time();
            $result = $this->model->allowField(true)->insertGetId($params);
            $type=[];
            $all_cost=0;
            //$all_price=0;
            foreach ($event as $k=>$v){
                $cost=$v["price"]*$v["number"];
                $type_name=\app\common\model\card\Type::field("name,price")->where(["id"=>$v["card_type_id"]])->find();
                $type[$k]=[
                    "card_type_id"=>$v["card_type_id"],
                    "card_type_name"=>$type_name["name"],
                    "card_kabaw_id"=>$result,
                    "number"=>$v["number"],
                    "price"=>$v["price"],
                    "all_cost"=>$cost,
                    "highest_price"=>$type_name["price"],
                    //"all_price"=>$v["all_price"],
                ];
                $all_cost+=$cost;
                //$all_price+=$v["all_price"];
            }
            if(!empty($type)){
                \app\common\model\card\Kabawtype::insertAll($type);
            }
            $this->model->where(["id"=>$result])->update(["all_cost"=>$all_cost]);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $type=\app\common\model\card\Kabawtype::field("*,1 selected_status")->where(["card_kabaw_id"=>$ids])->select();
            $row["event"]=json_encode($type,true);
            $typeList=\app\common\model\card\Type::all();
            /*foreach ($typeList as &$v){
                $v["selected_status"]=1;
                $type=\app\common\model\card\Kabawtype::where(["card_kabaw_id"=>$ids,"card_type_id"=>$v["id"]])->find();
                if(!empty($type))$v["selected_status"]=2;
            }*/
            $this->assign("typeList",$typeList);
            $this->view->assign('row_list', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        $res=$this->check($params);
        if(!$res) return $res;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            /*if($params["lifespan_data"]==1){
                unset($params["start_time"]);
                unset($params["end_time"]);
            }else{
                unset($params["fate"]);
            }*/
            $event=json_decode($params["event"],true);
            unset($params["event"]);
            $type=[];
            $all_cost=0;
            //$all_price=0;
            $unset_ids=[];
            $update=[];
            foreach ($event as $k=>$v){
                $cost=$v["price"]*$v["number"];
                $type_name=\app\common\model\card\Type::field("name,price")->where(["id"=>$v["card_type_id"]])->find();
                $type[$k]=[
                    "card_type_id"=>$v["card_type_id"],
                    "card_type_name"=>$type_name["name"],
                    "card_kabaw_id"=>$ids,
                    "number"=>$v["number"],
                    "price"=>$v["price"],
                    "all_cost"=>$cost,
                    "highest_price"=>$type_name["price"]
                    //"all_price"=>$v["all_price"],
                ];
                $unset_ids[]=$v["id"];
                if(empty($type_name)){
                    //$unset_ids[]=$v["id"];
                    unset($type[$k]);
                }else{
                    if(!empty($v["id"])){
                        $update[$k]=$type[$k];
                        $update[$k]["id"]=$v["id"];
                        unset($type[$k]);
                        //$update[$k]=$type[$k];
                    }
                }
                /*if(empty($v["id"])){
                    $unset_ids[]=$v["id"];
                }else{
                    $type[$k]["id"]=$v["id"];
                    $update[$k]=$type[$k];
                    unset($type[$k]);
                }*/
                $all_cost+=$cost;
                //$all_price+=$v["all_price"];
            }
            //删除卡券类型
            $model=new \app\common\model\card\Kabawtype();
            if(!empty($unset_ids)){
                \app\common\model\card\Kabawtype::whereNotIn("id",$unset_ids)->where(["card_kabaw_id"=>$ids])->delete();
            }
            if(!empty($type)){
                \app\common\model\card\Kabawtype::insertAll($type);
            }
            if(!empty($update)){
                $model->saveAll($update);
            }

            $params["all_cost"]=$all_cost;
            //$params["all_price"]=$all_price;
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            \app\common\model\card\Kabawtype::whereIn("card_kabaw_id",$ids)->delete();
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
    /**
     * 查看详情
     * */
    public function see($id)
    {
        $row = $this->model->get($id);
        $row["kabawtype"]=\app\common\model\card\Kabawtype::where(["card_kabaw_id"=>$id])->select();
        $this->assign("row",$row);
        return $this->view->fetch();
    }

}
